<template>
    <el-upload
        action="/admin/img/upload"
        :list-type="listType"
        :data="{type}"
        accept="image/jpg,image/jpeg,image/png"
        name="filePhoto"
        :auto-upload="true"
        :limit="limit"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :on-remove="handleUploadRemove"
        :before-upload="beforeUpload"
        :on-success="onUploadSuccess"
        :on-error="onUploadError"
        :on-preview="handlePreview"
        ref="uploader"
    >
        <slot>
            <el-icon><plus /></el-icon>
        </slot>
        <template #tip>
            <div class="el-upload__tip" v-if="tip">{{ tip }}</div>
        </template>
    </el-upload>

    <el-image 
        v-show="false"
        :preview-src-list="previewList" 
        hide-on-click-modal
        append-to-body
        ref="imageViewer"
    ></el-image>
</template>

<script>
export default {
    name: 'uploader'
}
</script>
<script setup>
import { toRefs, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ImageTypes } from '@/service/common'

const props = defineProps({
    type: {
        type: [Number, String],
        validator(val) {
            return Object.values(ImageTypes).includes(val)
        }
    },
    limit: {
        type: Number,
        default: 1
    },
    tip: {
        type: String,
        default: '支持PNG、JPG、JPEG格式，文件大小10K~10MB'
    },
    listType: {
        type: String,
        default: 'picture-card'
    },
    fileList: {
        type: Array,
        default: () => ([])
    }
})
const emits = defineEmits(['remove', 'success', 'error'])
const { type, limit, tip, listType } = toRefs(props)
const uploader = ref(null)
const imageViewer = ref(null)
const previewList = ref([])

function handleExceed(files, fileList) {
    console.log('[图片个数超出限制]', files, fileList)
    uploader.value.handleRemove(fileList[0])
    uploader.value.handleStart(files[0])
}

function handleUploadRemove() {
    emits('remove', type.value)
}

function beforeUpload(file) {
    console.log('[图片上传校验]', file)
    
    if (!/image\/(jpg|jpeg|png)/i.test(file.type)) {
        ElMessage.warning('上传图片只能是 PNG、JPG、JPEG 格式')
        return false
    }
    if (file.size <= 10*1024 || file.size >= 10*1024*1024) {
        ElMessage.warning('上传图片大小要求 10KB~10MB')
        return false
    }
}

function onUploadSuccess(resp) {
    emits('success', resp, type.value)
}

function onUploadError(err) {
    emits('error', err)
}

function handlePreview(file) {
    previewList.value = [file.url]
    imageViewer.value.showViewer = true
}
</script>
